<template>
  <div class="body-wrap">
    <div class="fb fs16 text-center">微信扫码登录</div>
    <div :loading="loading">
      <div class="qrCode-wrap">
        <div class="iframe-wrap">
          <div class="handle-wrap" v-show="!agreenProtocol">
            <div class="err-wrap no-agree">
              <el-button
                type="primary"
                size="small"
                class="agreen-btn"
                @click="agreenProtocol = true"
              >
                同意协议
              </el-button>
            </div>
          </div>
          <div class="handle-wrap" v-loading="loading" v-show="agreenProtocol">
            <div class="err-wrap" v-if="!loading && !wxurl">
              <svg-icon icon-class="no-signal" />
              <p>{{ wxOutError ? "登录超时" : "网络加载失败" }}</p>
              <el-button
                type="text"
                size="small"
                class="refresh-btn"
                @click="refresh"
              >
                <span>刷新试试</span>
              </el-button>
            </div>
            <div class="qrCode-icon" v-show="wxurl">
              <svg-icon icon-class="wechat" />
            </div>
            <div class="wx-wrap" ref="qrCode" v-show="wxurl" />
          </div>
        </div>
      </div>
    </div>
    <div class="protocol">
      <el-checkbox
        v-model="agreenProtocol"
        class="checkbox__text"
        label="1"
        true-value="1"
      >
        <div class="checkbox__text_inner">
          <span>已阅读并同意<a
            href="javascript:void(0)"
            @click="openLink(appCfg.userProtocol)"
            class="link-btn"
          >《用户协议》</a></span>
        </div>
      </el-checkbox>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted, onUnmounted } from "vue";
// @ts-ignore
import QRCode from "qrcodejs2-fix";
import { createGzhQrcode, checkGzhLogin, login } from "@/api/login";
import useMixins from "./mixins";
import { storeToRefs } from "pinia";
import { systemAppStore } from "@/stores/system";
import PsMessage from "@/components/message/index";
import { openLink } from "@/utils/costum-api"
const _systemAppStore_ = systemAppStore();
const { appInfo, appCfg } = storeToRefs(_systemAppStore_);
const { onLoginFinish } = useMixins()
const loading = ref(true)
const qrCode  = ref(null)
const wxurl = ref('')
const wxOutError = ref(false)
const agreenProtocol = ref(true);
let timerNum = 0, timer: number | null, ticket: string, qrcode: any
onMounted(() => {
  agreenProtocol.value && getPartyParam();
  const container = qrCode.value;
  qrcode = new QRCode(container, {
    text: '',
    width: 140,
    height: 140,
    colorDark: "#000000",
    colorLight: "#ffffff",
    correctLevel: QRCode.CorrectLevel.L,
  });
})
onUnmounted(() => {
  timer && clearTimeout(timer);
})
watch(agreenProtocol, () => {
  if (agreenProtocol.value) {
    if(wxurl.value){
      setTime();
    }else{
      getPartyParam();
    }
  }else{
    timer && clearTimeout(timer);
  }
})
/**
 * 获取第三方登录参数
 */
function getPartyParam() {
  loading.value = true;
  wxOutError.value = false;
  timerNum = 0;
  createGzhQrcode({
    expire_seconds: 82800,
    extra: {
      app_id: appInfo.value.appID,
      scene: "login",
      version: "v2",
    },
  })
    .then((res) => {
      const data = res.data || {};
      wxurl.value = data.url;
      ticket = data.ticket as string;
      qrcode && qrcode.makeCode(data.url);
      qrcode._el.title = "";
      loading.value = false;
      setTime();
    })
    .catch(() => {
      PsMessage.closeAll();
      loading.value = false;
    });
}
function setTime() {
  timer && clearTimeout(timer);
  if (++timerNum > 90) {
    wxOutError.value = true;
    wxurl.value = "";
    return;
  }
  timer = setTimeout(() => {
    checkGzhLogin({ ticket })
      .then((res) => {
        if (res.data) {
          onWxLoginFinish({ code: res.data });
        } else {
          setTime();
        }
      })
      .catch(() => {
        setTime();
      });
  }, 2000) as unknown as number;
}
/**
 * 刷新二维码
 */
function refresh() {
  getPartyParam();
}
function onWxLoginFinish({ code }: any = {}) {
  const params = {
    type: "wx_official_account",
    authCode: code, // 第三方登录授权码
    grantType: "authorization_code", // 授权类型 client_credentials: 客户端凭证 authorization_code:授权码
    channel: appInfo.value.channel, // 渠道信息
    uuid: appInfo.value.uuid, // 设备信息
    device_name: appInfo.value.device_name, // 设备名称
    version: appInfo.value.version,
  };
  login(params)
    .then((res) => {
      const data = res.data || {};
      data.isAutoLogin = true;
      data.isLogin = true;
      data.loginType = "wxLogin";
      onLoginFinish(data);
    })
    .catch(() => {
      refresh();
    });
}
</script>

<style lang="scss" scoped>
.body-wrap {
  margin: 60px 38px 0;
}
.qrCode-wrap {
  position: relative;
  width: 160px;
  height: 160px;
  margin: 10px auto 45px;
}

.iframe-wrap {
  position: relative;
  height: 100%;
  z-index: 2;
}

.handle-wrap {
  position: relative;
  height: 100%;

  :deep(.el-loading-spinner .circular) {
    width: 24px;
    height: 24px;
  }

  // :deep(.el-loading-mask) {
  //   border-radius: 6px;
  //   background: #494a4f;
  // }
}

.wx-wrap {
  padding: 10px;
  background: #fff;
  border-radius: 6px;
  overflow: hidden;
}

.err-wrap {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  font-size: 12px;
  color: #999999;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  border-radius: 6px;
  &.no-agree {
    background: url(./timeout-code.png) center center / cover;
  }
  .svg-icon {
    font-size: 64px;
    margin-bottom: 10px;
  }
}
.protocol {
  padding-top: 15px;
  border-top: 1px solid var(--el-border-color-lighter);
  text-align: center;
  .link-btn{
    --text-color: inherit;
  }
}
.qrCode-icon {
  display: flex;
  position: absolute;
  padding: 1px;
  top: 50%;
  left: 50%;
  margin-left: -14px;
  margin-top: -14px;
  color: rgba(9, 187, 7, 1);
  font-size: 26px;
  background: #fff;
  border-radius: 3px;
}
</style>
